package look.word.datasource.config;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

/**
 * @author : look-word
 * 2022-10-10 22:56
 **/
//@Component
//@Primary
public class MyDataSource implements DataSource {

    /**
     * 使用ThreadLocal而不是String，可以在多线程的时候保证数据的可靠性
     */
    public static ThreadLocal<String> flag = new ThreadLocal<>();


    private DataSource mysqlDataSource1;

    private DataSource mysqlDataSource2;

    public MyDataSource() { // 使用构造方法初始化ThreadLocal的值
        flag.set("one");
    }

    @Override
    public Connection getConnection() throws SQLException {
        // 通过修改ThreadLocal来修改数据源，
        // 为什么通过修改状态就能改变已经注入的数据源？ 这就得看源码了。
        if (flag.get().equals("one")) {
            return mysqlDataSource1.getConnection();
        }
        return mysqlDataSource2.getConnection();
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }
}
